---@class UITimeBoxQuickOpen : UIBase
UITimeBoxQuickOpen = UIBase.New(PanelResNames.UITimeBoxQuickOpen)
local t = UITimeBoxQuickOpen

local ErrorState_None = 0
local ErrorState_NotEnough = 1


function t.Init(_type, sequence, index,itemId)
    t.showType = _type
    t.sequence = sequence
    t.index = index
    t.itemId = itemId
    UIBase.Init(t)
end

function t:OnCreate()
    self.timeText = self:GetChild("time")
    ---@type GList
    self.itemList = self:GetChild("itemList")
    self.costIcon = self:GetChild("icon")
    self.curNumText = self:GetChild("curNum")
    self.boxIcon = self:GetChild("n245")
    self.curNumDefaultColor = self.curNumText.color
    self.needNumText = self:GetChild("needNum")
    self.sureBtn = self:GetChild("sureBtn")
    self.closeBtn = self:GetChild("closeBtn")
    self.ctrlState = self:GetController("ctrlState")
    self:SetDynamicList(self.itemList,self.ItemRender)
    self:RegisterOnClick(self.sureBtn, self.ClickSure)
    self:RegisterOnClick(self.closeBtn,self.ClickClose)
    self.timerUpdateId = 0
    self.errorState = ErrorState_None
    self.useCostType = 0 --0 免费 1钥匙，2钻石
end
function t:Refresh()
    self:InitData()
    self:RefreshItemList()
end
function t:RefreshItemList()
    local js = G.dataTable["t_stage"][tostring(logicMgr.MapManager.getMapId())]["f_MagicBox"..(self.itemModelId-200500)]
    self.itemDataList = logicMgr.ItemManager.ParseRewards(js)
    --self.itemDataList = self:GetDropByItemId(self.itemModelId)
    --table.sort(self.itemDataList,t.SortItem)
    self.itemList.numItems = #self.itemDataList
    self.itemList.scrollPane.touchEffect = #self.itemDataList > 4
end
function t.SortItem(a,b)
    if a.quality ~= b.quality then
        return a.quality > b.quality
    end
    return a.itemModelId < b.itemModelId
end
---@param go GComponent
function t:ItemRender(index,go)
    local data = self.itemDataList[index]
    local icon = go:GetChild("icon")
    local quality = go:GetChild("quality")
    local frame = go:GetChild("frame")
    self:SetItemAllById(icon,quality,frame,data.itemModelId)
    self:SetText(go:GetChild("num"),"")
    self:SetText(go:GetChild("rate"),"")
    self:SetText(go:GetChild("name"),logicMgr.ItemManager.GetItemName(data.itemModelId))
    go.onClick:Add(function()
        local showData = logicMgr.ItemManager.getItemConstDatabyModelId(data.itemModelId,true)
        showUI(PanelNames.UIBagItemInfo,showData);
    end)
end

function t:InitData()
    self:RemoveTimeCall(self.UpdateTime)
    self.goldNeedCount = -1
    if t.showType == logicMgr.UIShowManager.TimeBoxQuickOpenEnum.taskOpen then
        local info = TimeBoxHandler.GetTimeBoxInfo()[t.sequence]
        if not info then return end
        --local itemInfo = logicMgr.ItemManager.getItemData(info.idList[t.index])
        self.itemModelId = info.idList[t.index]

        self.startTime,self.endTime = TimeBoxHandler.GetBoxTime(t.sequence,t.index)
        --self.startTime = info.starTimeList[t.index]
        --self.endTime = self.startTime + cd
        self.ctrlState.selectedIndex = 1
        self:UpdateTime()
        self:TimeCall(self.UpdateTime,1000,-1)
    else
        local info = logicMgr.ItemManager.getItemData(self.itemId)
        self.itemModelId = info.itemModelId
        self.timeText.text = ""
        self.ctrlState.selectedIndex = 1
    end
    local cfg = dataTable.getRow("t_item", self.itemModelId)
    self.boxIcon.url = EnumConst.AtlasPath.ItemAtlas.. ItemManager.GetItemIcon(self.itemModelId)
    self.itemFunc = decodeJsonStrToTabel(cfg.f_ItemFunction)
    --local cd = self.itemFunc[2]
    local keyId = self.itemFunc[3]

    local cur = logicMgr.ItemManager.getBagNumByTableID(keyId)
    local need = 1
    if cur > 0 then
        self.curNumText.text = cur
        self.needNumText.text = "/"..need
        self:SetIconById(self.costIcon,keyId,EnumConst.ItemShowType.ITEM)
        self.useCostType = 1
        self:SetCostColor(cur<need)
    else --宝石来凑
        self:SetIconById(self.costIcon,CurrencyEnum.GOLD,EnumConst.ItemShowType.ITEM)
        local cur = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD)
        self.curNumText.text = getNumString(cur)
        t:RefreshGoldNeedCost()
    end

end
function t:SetCostColor(isRed)
    if isRed then
        self.curNumText.color = Color.red
        self.errorState = ErrorState_NotEnough
    else
        self.curNumText.color = Color.green
        self.errorState = ErrorState_None
    end
end

function t:RefreshGoldNeedCost()
    local time = 0
    if t.showType == logicMgr.UIShowManager.TimeBoxQuickOpenEnum.taskOpen then
        if self.startTime > HelperFunc.GetServerTime() then
            time = self.endTime - self.startTime--TimeBoxHandler.GetBoxOriginCD(self.itemModelId)
        else
            time = self.endTime- HelperFunc.GetServerTime()
        end
    else
        time = TimeBoxHandler.GetBoxOriginCD(self.itemModelId)
    end
    local need = dataTable.getDataTableByStringId("t_global","108").f_int_value
    local need = math.ceil(time/need)
    if need == self.goldNeedCount then
        return
    end
    self.goldNeedCount = need
    local cur = logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD)
    self.useCostType = 2
    self.needNumText.text = "/"..need
    self:SetCostColor(cur < need)
end
function t:UpdateTime()
    local cur = HelperFunc.GetServerTime()
    local time =  self.endTime- cur
    if(cur < self.startTime) then
        self.timeText.text = string.format(getLanguage("TimeBoxCountDownShowHourTip"),self:GetHourTip(self.endTime-self.startTime))
        return
    end
    self.timeText.text = string.format(getLanguage("TimeBoxCountDownTime"),HelperFunc.GetTimeStr(time))--string.format("在[color=#B7FF69]%s[/color]后可免费领取"
    if time <= 0 then
        self.timeText.text = getLanguage("TimeBoxCountDownFreeTime")--"免费领取"
        self:RemoveTimeCall(self.UpdateTime)
        self.timerUpdateId = 0
        self.ctrlState.selectedIndex = 0
        self.errorState = ErrorState_None
        self.useCostType = 0
    end
    if self.useCostType == 2 then
        self:RefreshGoldNeedCost()
    end
end
function t:GetHourTip(second)
    local str = ""
    local hour = math.floor((second ) / 3600)
    local min = math.floor((second - hour*3600)/60)
    if hour > 0 then
        str = string.format(getLanguage("Sys_Time_Hour"),hour)
    end
    if min >0 then
        str = str .. string.format(getLanguage("Sys_Time_Minute"),min)
    end
    return str
end
--获取固定掉落
function t:GetDropByItemId(itemModelId)
    local cfg = dataTable.getRow("t_item",itemModelId)
    if not cfg then
        return nil
    end
    local dropCfg = G.dataTable["t_drop"]
    for k,v in pairs(dropCfg) do
        local id = v.f_DropPoolId;
        if tonumber(self.itemFunc[1]) == tonumber(id) then
            dropCfg = v
            break
        end
    end
    if not dropCfg then return nil end
    local tb = decodeJsonStrToTabel(dropCfg.f_Content)
    local items = {}
    for k,v in pairs(tb) do
        local cfg1 = dataTable.getRow("t_item",v[1])
        local item = {
            itemModelId = v[1],
            num = v[2],
            icon = cfg1.f_Icon,
            quality = cfg1.f_Quality,
        }
        table.insert(items,item)
    end
    return items
end

function t:ParseItemFunc(str)
    self.itemFunc = decodeJsonStrToTabel(str)
end
function t:OnEnable()
    self:Refresh()
end
function t:OnDisable()
    self:RemoveTimeCall(self.UpdateTime)
end
function t:OnDestroy()

end

function t:ClickSure()
    if self.errorState == ErrorState_NotEnough then
        UISysTips.AddMsg(getLanguage("common_item_not_enough_tip"))
        return
    end

    if self.showType == logicMgr.UIShowManager.TimeBoxQuickOpenEnum.taskOpen then
        local state = 0
        if self.ctrlState.selectedIndex == 1 then --钥匙开启
            state = 2
        end
        TimeBoxHandler.SetRewardShowId(TimeBoxHandler.GetBoxId(t.sequence,t.index))
        TimeBoxHandler.ReqTimeBoxReward(state,t.sequence-1,t.index-1)
    else
        --TimeBoxHandler.ReqTimeBoxReward(3,t.sequence-1,t.index,t.itemId)
        local itemData = {};
        itemData["itemId"] = self.itemId
        itemData["itemModelId"] = self.itemModelId
        itemData["itemNum"] = 1;
        itemData["parameters"] = {};
        itemHandler.sendReqUseItem(itemData);
    end
    self:ClickClose()
end
function t:ClickClose()
    closeUI(PanelResNames.UITimeBoxQuickOpen)
end

return t
